<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="mini" :inline="true" v-show="showSearch"
             label-width="68px" style="display: flex; justify-content: flex-end;">

      <el-form-item label="日期" prop="activityDate">
        <el-date-picker
          v-model="queryParams.dateTime"
          type="datetimerange"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
<!--        <el-input-->
<!--          v-model=""-->
<!--          placeholder="请输入活动日期"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
      </el-form-item>
      <el-form-item label="名称" prop="activityName">
        <el-input
          v-model="queryParams.activityName"
          placeholder="请输入活动名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="负责人" prop="leaderName">-->
<!--        <el-input-->
<!--          v-model="queryParams.leaderName"-->
<!--          placeholder="请输入活动负责人"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button
          type="danger"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >活动申请</el-button>
      </el-form-item>

    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-divider content-position="left">活动列表-<span style="color: #999; font-size: 10px;">通过申请后的活动将无法修改</span></el-divider>
    </el-row>

    <el-table :data="activitiesList" stripe @selection-change="handleSelectionChange" >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="公寓名称" align="center" prop="apartmentName" fixed show-overflow-tooltip/>
      <el-table-column label="活动时间" align="center" prop="activityDate" fixed   show-overflow-tooltip/>
      <el-table-column label="活动名称" align="center" prop="activityName" fixed  show-overflow-tooltip />
      <el-table-column label="活动描述" align="center" prop="activityDescription" fixed show-overflow-tooltip />
      <el-table-column label="活动状态" align="center" prop="applyStatus" fixed >
        <template slot-scope="scope">
          <el-tag  v-if="scope.row.applyStatus === '申请中'" type="danger">申请中</el-tag>
          <el-tag v-if="scope.row.applyStatus === '通过'" type="success">通过</el-tag>
          <el-tag v-if="scope.row.applyStatus === '驳回'" type="info">驳回</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="参与人数" align="center" prop="participantCount" fixed  show-overflow-tooltip/>
      <el-table-column label="活动预算" align="center" prop="activityPrice" fixed show-overflow-tooltip />
      <el-table-column label="活动负责人" align="center" prop="leaderName" fixed show-overflow-tooltip />
      <el-table-column label="活动视频预览" align="center" prop="activityUrl" fixed >
        <template slot-scope="scope">
            <el-button
              type="success"
              plain
              @click="playVideo(scope.row.activityUrl)"
              ref="btn"
              size="mini"
            >视频预览
            </el-button>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="notes" fixed />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200px">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-upload2"
            @click="handleVideoUpload(scope.row)">
            视频上传
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改公寓活动对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" :disabled="isShow">
        <el-form-item label="公寓名称" prop="apartmentId">
          <el-select v-model="form.apartmentId" clearable placeholder="请选择">
            <el-option
              v-for="item in apartmentList"
              :key="item.apartmentId"
              :label="item.apartmentName"
              :value="item.apartmentId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="活动日期" prop="activityDate">
          <el-date-picker
            v-model="form.activityDate"
            type="date"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="活动名称" prop="activityName">
          <el-input v-model="form.activityName" placeholder="请输入活动名称" />
        </el-form-item>
        <el-form-item label="活动描述" prop="activityDescription">
          <el-input v-model="form.activityDescription" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="参与人数" prop="participantCount">
          <el-input v-model="form.participantCount" placeholder="请输入参与人数" />
        </el-form-item>
        <el-form-item label="活动金额" prop="activityPrice">
          <el-input-number v-model="form.activityPrice" :step="100"></el-input-number>
<!--          <el-input size="mini" v-model="form.activityPrice"></el-input>-->
        </el-form-item>
        <el-form-item label="备注" prop="notes">
          <el-input v-model="form.notes" placeholder="请输入未通过备注" />
        </el-form-item>
        <el-form-item label="负责人" prop="leaderName">
          <el-input v-model="form.leaderName" placeholder="请输入负责人" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="title" :visible.sync="openUpload" width="500px" append-to-body>
      <el-form ref="form" :model="form" label-width="80px">
          <el-form-item label="附件" prop="url">
            <el-upload
              ref="upload"
              :before-upload="beforeUpload"
              :auto-upload="false">
              <el-button slot="trigger" size="small" type="primary">选择文件</el-button>
              <el-button style="margin-left: 10px;" size="small" type="primary" @click="handleUpload">上传</el-button>
            </el-upload>
          </el-form-item>
      </el-form>
      <el-divider content-position="left">注：只可上传一个视频,格式为mp4,大小不超过1G<span style="color: #999; font-size: 10px;"></span></el-divider>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitActivitiesVideo">确 定</el-button>
        <el-button @click="cancelUPVideo">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogVisible">
      <vue-core-video-player :src="videoUrl"></vue-core-video-player>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listActivities,
    getActivities,
    delActivities,
    addActivities,
    updateActivities,
    updateActivitiesVideo, getActivitiesVideo
  } from "@/api/business/activities";
import {fileUpload, getElderApartment} from "@/api/business/elderInfo";
import {getMemberInfoList} from "@/api/business/memberInfo";

export default {
  name: "Activities",
  data() {
    return {
      isShow:false,
      videoUrl:"",
      dialogVisible: false,
      titleName:"",
      videoList : {},
      drawer: false,
      //从右侧打开
      direction: 'rtl',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 公寓活动表格数据
      activitiesList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openUpload:false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        dateTime:null,
        activityDate: null,
        activityTime: null,
        activityName: null,
        leaderName: null,
      },
      // 表单参数
      form: {activityPrice:0},
      memberList:{},
      apartmentList:{},
      // 表单校验
      rules: {
        apartmentId: [
          { required: true, message: "公寓不能为空", trigger: "blur" }
        ],
        activityDate: [
          { required: true, message: "活动日期不能为空", trigger: "blur" }
        ],
        activityName: [
          { required: true, message: "活动名称不能为空", trigger: "blur" }
        ],
      },
      user:{},
    };
  },
  created() {
    this.getList();
    this.getElderApartmentInfo();
    this.getMemberInfoList();
    this.user = this.$store.state.user;
  },
  methods: {
    /** 查询公寓活动列表 */
    getList() {
      this.loading = true;
      if(this.queryParams.dateTime != null) {
        const time = this.queryParams.dateTime;
        this.queryParams.startTime = time[0];
        this.queryParams.endTime = time[1]
      }
      listActivities(this.queryParams).then(response => {
        console.log(response.rows);
        this.activitiesList = response.rows;
        this.total = response.total;
        this.loading = false;
      }).catch(error =>{
        console.error(error);
      });

    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 取消按钮
    cancelUPVideo() {
      this.openUpload = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        activityId: null,
        apartmentId: null,
        activityDate: null,
        activityTime: null,
        activityName: null,
        activityUrl : null,
        activityDescription: null,
        applyStatus: null,
        leaderName: null,
        leaderId: null,
        participantCount: null,
        notes: null,
        createUserId: null,
        createTime: null,
        updateUserId: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.activityId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加公寓活动";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const activityId = row.activityId
      getActivities(activityId).then(response => {
        this.form = response.data;
        if(this.form.applyStatus === 2){
          this.isShow = true;
        }
        this.open = true;
        this.title = "修改公寓活动";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.activityId != null) {
            this.form.updateUserId = this.user.id;
            updateActivities(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.createUserId = this.user.id;
            addActivities(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    submitActivitiesVideo(){
      this.$refs["form"].validate(valid => {
        if (valid) {
          updateActivitiesVideo(this.form).then(response => {
            this.$modal.msgSuccess("添加成功");
            this.openUpload = false;
            // this.open = false;
            this.getList();
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const activityIds = row.activityId
      this.$modal.confirm('是否确认删除公寓活动编号为"' + activityIds + '"的数据项？').then(function() {
        return delActivities(activityIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/activities/export', {
        ...this.queryParams
      }, `activities_${new Date().getTime()}.xlsx`)
    },
    getElderApartmentInfo(){
      getElderApartment().then(response =>{
        this.apartmentList = response.rows
      })
    },
    getMemberInfoList(){
      getMemberInfoList().then(response =>{
        this.memberList = response.data;
        console.log(this.memberList);
      })
    },
    //活动视频上传弹出页面
    handleVideoUpload(row){
      this.form = row;
      this.openUpload = true;
      this.title = "活动视频上传";
    },
    //** 查看活动视频
    checkActVideo(row){
      // this.drawer = true
      const act = {activityId:row.activityId}
      //获取该活动下的视频内容
      getActivitiesVideo(act).then(response => {
        this.videoList = response.data;
        this.form.activityUrl = response.data.activityUrl;
        if(this.form.activityUrl == null){
          this.$message({
            message: '该活动暂未上传视频',
            type: 'warning'
          });
          return;
        }
        window.open(this.form.activityUrl);
        // this.openNewUrl(this.form.activityUrl);
        console.log(this.videoList);
        console.log(this.form.activityUrl);
      });
    },
    openNewUrl(url){
      let path=window.location.protocol+'//'+url
      window.location.href=path
    },
    beforeUpload(file) {
      // 处理上传文件之前的逻辑，例如限制文件类型和大小等
      // ...省略相关代码...
      console.log(file)
      return true; // 返回 true 以继续上传文件
    },
    //文件上传
    handleUpload() {
      const uploadComponent = this.$refs.upload; // 引用上传组件
      const file = uploadComponent.uploadFiles[0]; // 获取选择的文件
      if (file) {
        // 构造 FormData 对象并添加文件参数
        const formData = new FormData();
        formData.append('file', file.raw); // 添加文件参数，注意使用 file.raw 获取原始文件对象
        //调用接口
        console.log(formData);
        fileUpload(formData).then(response => {
          // 处理响应结果
          this.form.activityUrl = response;
          this.$modal.msgSuccess("上传成功!");
          console.log(response)
        }).catch(error => {
          // 处理错误
          this.$modal.msgError("上传失败!");
        });
      } else {
        // 处理未选择文件的情况
        this.$modal.msgWarning("请选择文件后上传");
      }
    },
    playVideo(url){
      this.dialogVisible = true;
      this.videoUrl = url;
    }
  }
};
</script>
<style scoped>
  .app-container{
    height: 650px;
  }
</style>
